using UnityEngine;
using System.Collections;

public class AutomaticRotation : MonoBehaviour
{
    #region Attributes

    public bool pingPong = false;
    public bool continuous = false;
    public Vector3 rotatingAxis = Vector3.zero;
    public float speed = 10.0f;
    public float distance = 90.0f;
    public bool resetScript = false;

    private bool movementComplete = false;
    private Quaternion startPosition;
    private Quaternion endPosition;

    #endregion

    #region Methods

    private void calculatePositions()
    {
        this.startPosition = this.transform.rotation;
        this.endPosition = this.startPosition * Quaternion.Euler(this.rotatingAxis * this.distance);
    }

    #endregion

    #region Unity Methods

    // Use this for initialization
    void Start()
    {
        calculatePositions();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (!movementComplete)
        {
            Quaternion displacement = Quaternion.Euler(this.rotatingAxis * this.speed * Time.deltaTime);
            this.transform.rotation *= displacement;

            //if (!this.continuous && Quaternion.Angle(this.transform.rotation, this.endPosition) <= this.speed * 0.1f)
            if (!this.continuous && this.transform.rotation == this.endPosition)
            {
                if (!this.pingPong)
                {
                    this.movementComplete = true;
                }
                else
                {
                    this.rotatingAxis *= -1;
                    calculatePositions();
                }
            }
        }

        if (this.resetScript)
        {
            this.movementComplete = false;
            calculatePositions();
            this.resetScript = false;
        }
    }

    #endregion
}